// initial state
import { StoreOptions } from "vuex";
import ACCESS_ENUM from "@/access/accessEnum";
import { UserControllerService } from "../../generated/user";

export default {
  namespaced: true,
  state: () => ({
    loginUser: {
      userName: "未登录",
      userRole: ACCESS_ENUM.NOT_LOGIN,
    },
  }),
  actions: {
    async getLoginUser({ commit }) {
      try {
        const res = await UserControllerService.getLoginUserUsingGet();
        if (res.code === 0) {
          commit("setUser", res.data);
          return true;
        }
      } catch (error) {
        commit("resetUser");
        return false;
      }
    },
    async logout({ commit }) {
      commit("resetUser");
      await UserControllerService.userLogoutUsingPost();
    },
  },
  mutations: {
    setUser(state, payload) {
      state.loginUser = {
        userName: payload.userName,
        userRole: payload.userRole || ACCESS_ENUM.USER,
      };
    },
    resetUser(state) {
      state.loginUser = {
        userName: "",
        userRole: ACCESS_ENUM.NOT_LOGIN,
      };
    },
  },
} as StoreOptions<any>;
